/* eslint-disable react/jsx-closing-tag-location */
import { useStore } from '@/hooks';
import { Button, Form } from '@alifd/next';
import { t } from '@lingui/macro';
import React, { useEffect, useRef, useState } from 'react';
import { column, DATETIME_TEXT } from './definitions';
import { observer } from 'mobx-react-lite';
import { observable } from 'mobx';
import TauTable from '@/components/TauTable';
import { uniqueId } from 'lodash';
import DetailDrawer from '../DetailDrawer';
import moment from 'moment';

const tableId = uniqueId('tauTable-');


/**
 * diff
 * @param {*} rootOrder
 * @param {*} currentOrder
 */
function diffChangeContent(rootOrder, currentOrder, changeArray) {
  if (!rootOrder || !currentOrder) {
    return changeArray;
  }
  const changeTickets = currentOrder.busOrder.orderDetails.filter((p) => rootOrder.busOrder.orderDetails.some((j) => j.ticketCode === p.ticketCode));
  if (changeTickets.length > 0) {
    let changeActive = null;
    const changeInfo = {
      content: {},
    };
    if (rootOrder.id !== currentOrder.id) {
      changeActive = true;
    }
    // 比较去程站点信息
    if (
      rootOrder.busOrder.from.cityText !== currentOrder.busOrder.from.cityText ||
      rootOrder.busOrder.from.stationName !== currentOrder.busOrder.from.stationName
    ) {
      changeActive = true;
      changeInfo.content.changeFromStation = `上车地址从 ${rootOrder.busOrder.from.cityText}-${rootOrder.busOrder.from.stationName} 改签到了 ${currentOrder.busOrder.from.cityText}-${currentOrder.busOrder.from.stationName}`;
    }

    if (
      rootOrder.busOrder.to.cityText !== currentOrder.busOrder.to.cityText ||
      rootOrder.busOrder.to.stationName !== currentOrder.busOrder.to.stationName
    ) {
      changeActive = true;
      changeInfo.content.changeToStation = `下车地址从 ${rootOrder.busOrder.to.cityText}-${rootOrder.busOrder.to.stationName} 改签到了 ${currentOrder.busOrder.to.cityText}-${currentOrder.busOrder.to.stationName}`;
    }

    // 判断是否是往返票，如果是，则比较回程信息
    if (rootOrder.busOrder.isRoundTrip) {
      if (
        rootOrder.busOrder.returnFrom.cityText !== currentOrder.busOrder.returnFrom.cityText ||
        rootOrder.busOrder.returnFrom.stationName !== currentOrder.busOrder.returnFrom.stationName
      ) {
        changeActive = true;
        changeInfo.content.changeReturnFromStation = `回程上车地址从 ${rootOrder.busOrder.returnFrom.cityText}-${rootOrder.busOrder.returnFrom.stationName} 改签到了 ${currentOrder.busOrder.returnFrom.cityText}-${currentOrder.busOrder.returnFrom.stationName}`;
      }
      if (
        rootOrder.busOrder.returnTo.cityText !== currentOrder.busOrder.returnTo.cityText ||
        rootOrder.busOrder.returnTo.stationName !== currentOrder.busOrder.returnTo.stationName
      ) {
        changeActive = true;
        changeInfo.content.changeReturnToStation = `回程下车地址从 ${rootOrder.busOrder.returnTo.cityText}-${rootOrder.busOrder.returnTo.stationName} 改签到了 ${currentOrder.busOrder.returnTo.cityText}-${currentOrder.busOrder.returnTo.stationName}`;
      }
    }

    // 比较每张车票的改签情况
    currentOrder.busOrder.orderDetails.forEach((ticket) => {
      const originalTicket = rootOrder.busOrder.orderDetails.find(
        (p) => p.ticketCode === ticket.ticketCode,
      );
      if (originalTicket) {
        if (originalTicket.shiftTime !== ticket.shiftTime) {
          changeActive = true;
          changeInfo.content.changeShiftTime = `车票的预计上车时间从 ${DATETIME_TEXT(originalTicket.shiftTime)} 改签到了 ${DATETIME_TEXT(ticket.shiftTime)}`;
        }
      }
    });
    if (changeActive) {
      changeInfo.fullname = rootOrder.busOrder.fullname;
      // const filterTicket = changeTickets.filter((p) => p.originalTicketCode);
      changeInfo.changeTickets = changeTickets;
      changeInfo.oldInfo = {
        id: rootOrder.id,
        price: rootOrder.price,
        crDate: DATETIME_TEXT(rootOrder.crDate),
      };
      changeInfo.newInfo = {
        id: currentOrder.id,
        price: currentOrder.price,
        crDate: DATETIME_TEXT(currentOrder.crDate),
      };
      changeArray.push(changeInfo);
    }
  }

  return changeArray;
}

function generateOrderChanges(orders) {
  const changesArray = [];

  // 根数据：即没有 changeAssociatedOrderIds 的订单
  const rootOrder = orders.find((p) => !p.changeAssociatedOrderIds);

  // 其他订单：即有 changeAssociatedOrderIds 的订单
  const otherOrders = orders.filter((p) => p.changeAssociatedOrderIds);

  // 根据改签顺序构建一个对象，key 为改签次数，value 为订单对象
  const rootObj = {
    0: [rootOrder],
  };

  for (let i = 0; i < otherOrders.length; i++) {
    const { changeBatch } = otherOrders[i];

    if (!rootObj[changeBatch]) {
      rootObj[changeBatch] = [];
    }

    rootObj[changeBatch].push(otherOrders[i]);
  }

  // 按顺序对比每一个改签订单与其前一个改签订单
  for (let i = 0; i <= otherOrders.length; i++) {
    const previousOrders = rootObj[i];
    const currentOrders = rootObj[i + 1];

    if (currentOrders) {
      // 对比当前所有订单与之前所有订单
      currentOrders.forEach((currentOrder) => {
        previousOrders.forEach((previousOrder) => {
          const diffResult = diffChangeContent(previousOrder, currentOrder, []);
          changesArray.push(...diffResult);
        });
      });
    }
  }
  return changesArray;
}

function Index({ orderId }) {
  const { busOrderStore: store } = useStore();
  const [orders, setOrders] = useState([]);
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [orderRefund] = useState(() => observable({}));
  const [modal, setModal] = useState([]);
  const orderRef = useRef();

  useEffect(() => {
    (async () => {
      if (orderId?.length > 0) {
        const res = await store.getChangeOrder([...orderId]);
        const changeResult = generateOrderChanges(res);
        // 排序
        const sortResult = changeResult.sort((a, b) => moment(b.newInfo.crDate).unix() - moment(a.newInfo.crDate).unix());
        setOrders(sortResult);
      }
    })();
  }, []);

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(orderRefund, name, value);
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleViewOrder = (id) => {
    orderRef.current = { id };
    setModal(['view']);
  };

  // Modal窗口关闭回调
  const handleCancel = () => {
    setModal([]);
  };

  return (
    <Form inline value={orderRefund} onChange={handleChange} useLabelForErrorMessage>
      <div className="content">
        <TauTable
          instanceId={tableId}
          // primaryKey="ticketCode"
          tableLayout="fixed"
          currentPage={0}
          pageSize={10}
          total={orders?.length}
          sort={store.tableSort}
          onFetch={(pg) => {
            store.pg = pg;
          }}
          dataSource={orders}
          hidePagination
          rowKey="oldInfo.id" // 设置每行的唯一标识
          fullname
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => i + 1 },
            column('changeId', {
              cell: (v, i, r) => {
                const { newInfo, oldInfo } = r;
                const tmpArray = [oldInfo.id, newInfo.id];
                return (
                  <>{tmpArray.map((p, index) => (
                    <React.Fragment key={index}>
                      <Button text type="primary" onClick={() => handleViewOrder(tmpArray[index], 'view')}>
                        {p}
                      </Button>
                      {index < tmpArray.length - 1 && ' >> '}
                    </React.Fragment>
                  ))}</>
                );
              },
              width: '25vw',
            }),
            column('fullname', {}),
            column('changePrice', {}),
            column('content', { width: '15vw' }),
            column('changeTickets', { width: '10vw' }),
            column('changeCrDate', { width: '20vw' }),
          ]}
        />
      </div>
      <DetailDrawer
        modal={modal}
        handleCancel={handleCancel}
        handleUpdate={() => { }}
        orderId={orderRef.current?.id}
        changeAssociatedOrderIds={orderRef.current?.changeAssociatedOrderIds || []}
        visible={modal[0] === 'view' || modal[0] === 'edit'}
        onClose={() => {
          setModal([...modal, `toClose$${Date.now()}`]);
        }}
      />
    </Form>
  );
}

export default observer(Index);
